/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package sUtils;

import java.io.*;
import javax.microedition.io.Connector;
import javax.microedition.sensor.*;

/**
 *
 * @author thomas.s
 */
public class MotionSensor implements DataListener
{
    SensorConnection sensor;
    EventListener parent;
    int x=0,y=0,z=0;
    public boolean on=true;

    public MotionSensor( EventListener p )
    {
        parent = p;
        SensorInfo[] sensors = SensorManager.findSensors(null,null);
        for ( int i=0; i<sensors.length; i++ )
        {
            if (sensors[i].getQuantity().equalsIgnoreCase("acceleration"))
            {
                try {
                    sensor = (SensorConnection) Connector.open(sensors[i].getUrl());
                    sensor.setDataListener(this, 1);
                } catch (IOException e) { }
                break;
            }
        }
    }

    public void dataReceived( SensorConnection conn, Data[] arg, boolean lost )
    {
        int nx= (int)(arg[0].getDoubleValues()[0]*10/19);
        int ny= (int)(arg[1].getDoubleValues()[0]*10/19);
        int nz= (int)(arg[2].getDoubleValues()[0]*10/19);
        if (nx!=x || ny!=y || nz!=z)
        {
            x=nx; y=ny; z=nz;
            if (on) parent.onEvent("motion",  x+" "+y+" "+z);
        }
    }

}
